# Kestrel: An XMPP-based Many-Task Computing Scheduler
# Author: Lance Stout <lancestout@gmail.com>
#
# Copyright 2009-2010 Clemson University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Log reader module.

The log reader module allows for analyzing log files from previous
application runs in order to recreate and plot events.
"""


class LogReader(object):
    """
    Read through an application log and recreate the sequence of events so
    that analysis can be performed.

    Events will be prepended with 'log/' in order to prevent conflicts with
    other running modules. Thus a 'presence/available' event recorded in the
    log would trigger a 'log/presence/available' event here.

    Events listened for by this module:
      analyzer/read

    Events raised by this module:
      log/*
      analyzer/read/complete
    """

    def __init__(self, kernel):
        """Instantiate a log reader."""
        self.kernel = kernel
        self.events = {'analyzer/read': self.read_log}
        self.kernel.register(self)

    def read_log(self, name=None):
        """
        Read through an application log and recreate the
        sequence of events so that analysis can be performed.

        Events will be prepended with 'log/' in order to
        prevent conflicts with other running modules. Thus
        a 'presence/available' event recorded in the log would
        trigger a 'log/presence/available' event here.
        """
        if name is not None:
            log = open(name)
            for line in log:
                try:
                    divider = line.index(']') + 1
                    header = line[0:divider]
                    body = line[divider:]

                    items = header.split(' ')
                    time = items[0]
                    event = items[1].strip('[]')

                    data = {'time': time,
                            'data': body}
                    self.kernel.event('log/' + event, data)
                except:
                    pass
            self.kernel.event('analyzer/read/complete')
